<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;

class Buyapi extends Controller
{
    public function __construct(Request $request){
        $this->data = $request->param();
        $this->user_id = session('userid') == null ? 1 : session('userid');
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
    }


    // 根据产品/产品角色获取相关信息
    public function getProList()
    {
        if(!isset($this->data['pro_id']) && $this->data['pro_id']=='') return json_encode(array('status'=>2,'msg'=>lang('incorrect_data_submission').' pro_id'));
        if(!isset($this->data['prochar_id']) && $this->data['prochar_id']=='') return json_encode(array('status'=>2,'msg'=>lang('incorrect_data_submission').' prochar_id'));

        // 获取历史采购单价（同一个prochar_id) 规则：365天之内最后三天的最小值
        $startTime = time()-365*24*60*60;
        // $price = min(getDatas('buy_plan',['price'],['create_at'=>['between',$startTime.','.time()],'pro_id'=>$this->data['pro_id'],'prochar_id'=>$this->data['prochar_id']],'id desc'));
        $lastYearPrice = Db::name('buy_plan')->field('price')->where(['create_at'=>['between',$startTime.','.time()],'pro_id'=>$this->data['pro_id'],'prochar_id'=>$this->data['prochar_id']])->limit(3)->order('id desc')->select();
        if(!empty($lastYearPrice)){
            $price = min($lastYearPrice);
        }else{
            $price = Db::name('buy_plan')->field('price')->where(['pro_id'=>$this->data['pro_id'],'prochar_id'=>$this->data['prochar_id']])->limit(1)->order('id desc')->select();
        }
        // dump($price);die;

        // 获取产品和产品角色的基本信息
        $proAndProchar = model('Buy')->getProAndProchar($this->data['pro_id'],$this->data['prochar_id'],$this->lang);

        // 获取产品/产品角色下的介绍类型：产品规格，装箱说明，其他备注 内容
        $prodesc_cat = model('Buy')->getProdesc_cat($this->data['pro_id'],$this->data['prochar_id']);
        // dump($prodesc_cat);die;

        // 获取产品/产品角色配件信息
        $pro_item = model('Buy')->getPro_item($this->data['pro_id'],$this->data['prochar_id'],$this->lang);
        // dump($pro_item);die;

        // 根据产品/产品角色获取历史记录，10条数据
        $history = getSearch('buy_plan','zu',['zu.po_id,zu.company_id,zu.qty,zu.price,zu.create_at,c.name'],['zu.pro_id'=>$this->data['pro_id'],'zu.prochar_id'=>$this->data['prochar_id'],'zu.po_id'=>['>',0]],[['company c','zu.company_id = c.id']],'zu.id desc');
        if(!empty($history)){
            foreach ($history as $k => $v) {
                $history[$k]['create_at'] = explode(' ',getTimeDates($v['create_at'],9,$this->lang))[0];
            }
        }

        // 装箱规格
        $norm = getDatas('prochar',['ctn_size,ctn_kgs,ctn_m3,qty'],['id'=>$this->data['prochar_id']],'id desc');

        // dump($history);die;
        $returnData['price'] = !empty($price) ? $price['price'] : 0;
        $returnData['proAndProchar'] = $proAndProchar;
        $returnData['prodesc_cat'] = $prodesc_cat;
        $returnData['pro_item'] = $pro_item;
        $returnData['history'] = $history;
        $returnData['norm'] = !empty($norm) ? $norm[0] : [];
        // dump($returnData);die;
        return json_encode($returnData);
    }
        // 产品角色ID，MODEL,产品名称 search搜索
    public function searchData()
    {
        if(isset($this->data['searchText']) && $this->data['searchText']){
            if(isset($this->data['proclass']) && $this->data['proclass']) $searchWhere['pt.procat_id'] = $this->data['proclass'];
            $searchWhere['mu.content|zu.id|zu.model'] = ['like','%'.$this->data['searchText'].'%'];
            $searchWhere['mu.lang'] = $this->lang;
            $pro_prochar_data = Db::name('prochar')
                                    ->alias('zu')
                                    ->join([
                                                ['pro p','zu.pro_id = p.id','LEFT'],
                                                ['multi_lang mu','p.mkey = mu.mkey','LEFT'],
                                                ['pro_brand b','p.brand_id = b.id','LEFT'],
                                                ['pro2cate pt','p.id = pt.pro_id','LEFT']
                                            ])
                                    ->field(['zu.*,mu.content,b.name brand_name'])
                                    ->where($searchWhere)
                                    ->limit(10)
                                    ->select();
            if(!empty($pro_prochar_data)){
                foreach ($pro_prochar_data as $k1 => $v1) {
                    $feature = model('Buy')->getFeature($v1['pro_id'],$v1['id'],$this->lang);
                    $pro_prochar_data[$k1]['feature'] = '';
                    $pro_prochar_data[$k1]['feature'] .= $v1['id']. '/'.$v1['brand_name'].'/'.$v1['model'].'/'.$v1['content'];
                    if(!empty($feature)){
                        foreach ($feature as $k2 => $v2) {
                            $pro_prochar_data[$k1]['feature'] .= '/'.$v2['value'];
                        }
                    }
                    // rtrim($pro_prochar_data[$k1]['feature'],'/');
                }
            }
            // dump($pro_prochar_data);die;
            return json_encode($pro_prochar_data);
        }
    }

    // 根据公司ID，获取联系人信息和银行账号信息
    public function getCompanyLinkman()
    {   
        if(!isset($this->data['id'])) return json_encode(array('status'=>2,'msg'=>lang('please_select_company')));
        return json_encode(model('Buy')->getCompanyLinkmans($this->data['id']));
    }

    //获取公司详情
    public function getCompanyInfo()
    {
        if(!isset($this->data['id']) || $this->data['id'] == 0) return json_encode(array('status'=>2,'msg'=>lang('please_select_company')));
        $join = [
                    ['co_profile pi','zu.id = pi.co_id','LEFT'],
                    ['admin a','zu.saler_id = a.id','LEFT']
                ];
        $company = getSearch('company','zu',['zu.*,pi.addr,pi.zipcode,a.nickname'],['zu.id'=>$this->data['id']],$join,'zu.id asc');
        if(!empty($company)){
            $company[0]['create_name'] = $company[0]['create_id'] == '' ? '-' : getinfo($company[0]['create_id'], 'admin')['nickname'];//编辑者
            $company[0]['create_time'] = $company[0]['create_at'] == '' ? '-' : getTimeDate($company[0]['create_at'],9);
            return json_encode($company[0]);
        }else{
            return json_encode($company);
        }
    }

    // 获取公司名称
    public function searchCompany()
    {
        if(!isset($this->data['searchCompany']) && !$this->data['searchCompany']) return json_encode(array('status'=>2,'msg'=>lang('please_enter_the_correct_search_information')));
        return json_encode(model('Buy')->searchCompany($this->data['searchCompany']));
    }

    public function hasterms()
    {
        $hasterms = hasData('buy_terms','1=1');
        if($hasterms){
            return array('status'=>1,'msg'=>lang('successfully'));
        } else{
            return array('status'=>0,'msg'=>lang("add_purchase_contract_terms"));
        }
    }

}
